package App.OO.ClientView;

import App.Model.Tool.DosTool;
import App.Model.Tool.SwingUtil;
import App.OO.service.OOLoginSignService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Objects;


/*登录界面*/
public class OOLoginFrame extends JFrame {
    private JTextField userId;
    private JPasswordField userPsw;
    private JLabel mention;
    private boolean loop = true;//显示菜单
    private String key = "";
    private OOLoginSignService loginService = new OOLoginSignService();

    //主菜单
    public boolean ShowMenu() {
        while (loop) {
            System.out.println("______OO______");
            System.out.println(" 1 : 登录");
            System.out.println(" 2 : 注册");
            System.out.println(" 9 : 退出");

            key = DosTool.readString(1);
            switch (key) {
                case "1"://登录
                    System.out.println("登录系统");
                    System.out.println("用户号码");
                    String userId = DosTool.readString(50);
                    System.out.println("用户密码");
                    String userPsw = DosTool.readString(50);

                    //code//服务器数据库验证
                    int loginState = loginService.checkUser(userId, userPsw);
                    if (loginState == 1) {                                                    //此处逻辑更改
                        return true;
                    } else {
                        System.out.println("login error");
                    }
                    break;
                case "2"://第一次注册
                    OOSignFrame ooSignView = new OOSignFrame();
                    if (ooSignView.OOSign()) {//成功则退出
                        loginService.setUser(ooSignView.getUser());
                        loginService.setSocket(ooSignView.getSocket());
                        return true;
                    }
                    break;
                case "9":
                    loop = false;
                    break;
                default:

            }
        }
        return false;
    }

    public OOLoginSignService getLoginService() {
        return loginService;
    }

    public void showLoginFrame() {
        Font textFont = new Font("宋体", Font.BOLD, 17);
        setTitle("OO登录");
        setBounds(400, 300, 400, 250);    //设置窗体显示位置和大小
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        //底部注册与登录按钮
        JPanel PanelSough = new JPanel(new FlowLayout());
        JButton signButton = new JButton("注册");
        JButton jLoginBtn = new JButton("登录");
        signButton.setFont(textFont);
        jLoginBtn.setFont(textFont);
        signButton.setPreferredSize(new Dimension(100, 25));
        jLoginBtn.setPreferredSize(new Dimension(100, 25));
        PanelSough.add(jLoginBtn);
        PanelSough.add(signButton);

        //程序icon标
        setIconImage(new ImageIcon("src\\main\\resources\\recourse\\OO.png").getImage());

        //顶部OO图标
        JPanel PanelNorth = new JPanel(new FlowLayout());
        JLabel ooLabel = new JLabel();
        int width = 63, height = 72;
        ImageIcon image = SwingUtil.createAutoAdjustIcon("src\\main\\resources\\recourse\\OO.png", false);//实例化ImageIcon 对象
        //image.setImage(image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT ));
        ooLabel.setIcon(image);
        ooLabel.setPreferredSize(new Dimension(width, height));
        PanelNorth.add(ooLabel);
        //老方法,毛边严重
//        JPanel PanelNorth = new JPanel(new FlowLayout());
//        JLabel ooLabel = new JLabel();
//        int width = 77,height = 89;
//        ImageIcon image = new ImageIcon("App\\recourse\\OO.png");//实例化ImageIcon 对象
//        image.setImage(image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT ));
//        ooLabel.setIcon(image);
//        ooLabel.setSize(width, height);
//        PanelNorth.add(ooLabel);


        //中间账号与密码输入框
        JPanel panelCenter = new JPanel(new FlowLayout());
        JPanel panelCenter_one = new JPanel(new FlowLayout());
        JPanel panelCenter_tow = new JPanel(new FlowLayout());
        JPanel panelCenter_thr = new JPanel(new FlowLayout());
        mention = new JLabel("                                               ");
        userId = new JTextField("Arisu", 22);
        userPsw = new JPasswordField("1230", 22);
        userPsw.setEchoChar('●');//隐藏密码
        userId.setCaretPosition(userId.getText().length());//光标移至末尾
        JLabel jLabel = new JLabel("账号: ");
        jLabel.setFont(textFont);
        JLabel jLabel_ = new JLabel("密码: ");
        jLabel_.setFont(textFont);

        //添加显示密码的按钮
        JButton toggleButton = new JButton("●");
        toggleButton.setFont(new Font("像素字体", Font.BOLD, 10));
        toggleButton.setPreferredSize(new Dimension(18, 20));
        toggleButton.addActionListener(new ActionListener() {
            boolean isPasswordVisible = false;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (isPasswordVisible) {
                    userPsw.setEchoChar('●'); // 隐藏密码
                } else {
                    userPsw.setEchoChar((char) 0); // 显示密码
                }
                isPasswordVisible = !isPasswordVisible;
            }
        });

        panelCenter_one.add(jLabel);
        panelCenter_one.add(userId);
        panelCenter_one.add(new JLabel("     "));
        panelCenter_tow.add(jLabel_);
        panelCenter_tow.add(userPsw);
        panelCenter_tow.add(toggleButton);
        panelCenter_thr.add(mention);
        panelCenter.add(panelCenter_one);
        panelCenter.add(panelCenter_tow);
        panelCenter.add(panelCenter_thr);

        //事件处理
        userId.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (userId.getCaret() != null && !Objects.equals(userId.getText(), "")) {
                        userPsw.requestFocusInWindow(); // 请求焦点到第二个文本框
                        userPsw.setCaretPosition(userPsw.getPassword().length);//光标移至末尾
                    }
                }
            }
        });
        userPsw.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (userPsw.getCaret() != null && !userPsw.getText().equals("") && !Objects.equals(userId.getText(), "")) {
                        loginConfirm();
                    } else {
                        if (userPsw.getText().equals("")) {
                            mention.setText("   请输入密码   ");
                        } else if (!Objects.equals(userId.getText(), "")) {
                            mention.setText("   请输入账号   ");
                        }
                    }
                }
            }
        });
        signButton.addActionListener(e -> {//跳转注册页面
            new OOSignFrame().showSignFrame();
        });
        jLoginBtn.addActionListener(e -> {//判断登录结果后进入二级界面
            loginConfirm();
        });

        //布局
        setLayout(new BorderLayout());
        add(PanelSough, BorderLayout.SOUTH);
        add(PanelNorth, BorderLayout.NORTH);
        add(panelCenter, BorderLayout.CENTER);
        setVisible(true);

    }

    public void loginConfirm() {
        String SUserId = userId.getText();
        String SPassword = userPsw.getText();
        System.out.println(SUserId + "  |  " + SPassword);

        //code//服务器数据库验证
        int loginState = loginService.checkUser(SUserId, SPassword);
        if (loginState == 0) {//登录成功,到OOMainFrame
            mention.setText("   服务器未启动   ");
            mention.setForeground(Color.red);
        } else if (loginState == 1){
            //关闭当前窗口并且(X)打开主窗口Frame(X)
            dispose();
        } else if(loginState == -1){//登录失败,重置账号(密码错误)
            mention.setText("   账号或密码错误   ");
            mention.setForeground(Color.red);
            userPsw.setText("");
            userPsw.requestFocusInWindow(); // 请求焦点到第二个文本框
        } else if(loginState == -2){//登录失败,重置账号(用户已登录)
            mention.setText("   该用户已登录   ");
            mention.setForeground(Color.red);
        }
    }
}
